#!/usr/bin/env python  
# encoding: utf-8


""" 
@version: v1.0 
@author: Shylock 
@license: Apache Licence  
@contact: JYFelt@163.com 
@site: http://blog.csdn.net/weixin_38034182 
@software: PyCharm Community Edition 
@file: MYSQL_CL.py 
@time: 2017/12/23 22:29 
"""
import MySQLdb as mdb

'''连接到数据库'''


def __connect(open):
    global cur
    global con
    if open == 1:
        try:
            # 连接 mysql 的方法：connect('ip','user','password','daname')
            con = mdb.connect('localhost', 'root', '*****', '***', charset='utf8')
            # 建立查询于cursor模块上
            cur = con.cursor()
            return cur, con

        except mdb as e:
            print(e)
    if open == 0:
        if con:
            con.close()


def exec(sql):
    # 连接数据库
    __connect(1)
    # 执行语句
    cur.execute(sql)

    # 取得上个查询的结果，是一个结果
    data = cur.fetchall()
    # 断开数据库
    __connect(0)
    # 返回data值以来调用
    return data


def update(sql):
    __connect(1)

    try:
        cur.execute(sql)
        con.commit()
        print('oj8k!')
    except:
        con.rollback()
    __connect(0)
exec('SELECT VERSION()')
print(exec('SELECT VERSION()'))